package com.silence.whereeat.servlet;

import com.silence.whereeat.dao.UserInfoDao;
import com.silence.whereeat.model.UserInfo;
import com.silence.whereeat.service.UserInfoService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 注册
 * Created by 伟阳 on 2015/9/14.
 */
public class RegisterServlet extends HttpServlet {

    private UserInfoService register;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        PrintWriter out = response.getWriter();
        if (register.isExist(username)) {
            out.println("failed");
        } else {
            UserInfo userInfo = new UserInfo(username, password);
            if (register.register(userInfo) > 0) {
                out.println("success");
            } else {
                out.println("failed");
            }
        }
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void init() throws ServletException {
        register = new UserInfoDao();
    }

    @Override
    public void destroy() {
        register.close();
    }
}
